package com.lmoumou.lib_calendarview.widget

import android.content.Context
import android.graphics.Color
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.lmoumou.lib_calendarview.R
import com.lmoumou.lib_calendarview.SuperDividerItemDecoration
import com.lmoumou.lib_calendarview.entity.DayAttrsBeen
import com.lmoumou.lib_calendarview.entity.DayBeen
import com.lmoumou.lib_calendarview.utils.CalendarUtils
import kotlinx.android.synthetic.main.item_calendar.view.*
import java.util.*

/**
 * @author:Lmoumou
 * @date:2019/11/5
 * 描述:
 **/
class CalendarAdapter(
    private val context: Context,
    private val onItemClick: (data: DayBeen, position1: Int, position2: Int) -> Unit
) :
    RecyclerView.Adapter<CalendarAdapter.CalendarViewHolder>() {

    private val mInflater: LayoutInflater by lazy { LayoutInflater.from(context) }

    private val itemDecoration by lazy { SuperDividerItemDecoration.Builder(context)
        .setDividerColor(Color.RED)
        .setDividerWidth(1)
        .setIsShowLastDivide(false)
        .build() }

    private var attrsMap: LinkedHashMap<String, DayAttrsBeen>? = null
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CalendarViewHolder =
        CalendarViewHolder(mInflater.inflate(R.layout.item_calendar, parent, false))

    override fun getItemCount(): Int = Int.MAX_VALUE

    override fun onBindViewHolder(holder: CalendarViewHolder, position: Int) {
        val calendar = Calendar.getInstance().apply {
            add(Calendar.MONTH, (position - CalendarView.currentPosition))
        }

        holder.itemView.mTextView.text =
            CalendarUtils.getDaysOfMoth(
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH) + 1
            )[8].toString()

        holder.itemView.mMothView.layoutManager = GridLayoutManager(context, 7)
        holder.itemView.mMothView.removeItemDecoration(itemDecoration)
        holder.itemView.mMothView.addItemDecoration(itemDecoration)
        val dataList =
            CalendarUtils.getDaysOfMoth(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, attrsMap)

        val mothAdapter = MothAdapter(context, dataList) { data, position2 ->
            onItemClick(data, position, position2)
        }
        holder.itemView.mMothView.adapter = mothAdapter
    }

    inner class CalendarViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

    fun setSpecialMap(map: LinkedHashMap<String, DayAttrsBeen>) {
        attrsMap = map
        notifyDataSetChanged()
    }
}